import React, { Component, Fragment } from 'react';
import TodoItem from './TodoItem';
import './style.css';

class TodoList extends Component {
  constructor (props) {
    super(props);
    this.state = {
      inputValue: '',
      list: []
    }
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleBtnClick = this.handleBtnClick.bind(this);
    this.handleItemDelete = this.handleItemDelete.bind(this);
  }

  render () {
    return (
      <Fragment>
        {
          // 用htmlFor代替原生的for
        }
        <div>
          <label htmlFor="insertArea">输入内容</label>
          <input
            id="insertArea"
            className="input"
            value={this.state.inputValue}
            onChange={this.handleInputChange} />
          <button onClick={this.handleBtnClick}>提交</button>
        </div>
        <ul>
          {this.getTodoItem()}
        </ul>
      </Fragment>
    )
  }

  handleInputChange (e) {
    const value = e.target.value
    this.setState(() => ({
        inputValue: value
    }));
  }

  handleBtnClick () {
    this.setState((prevState) => ({
      list: [...prevState.list, prevState.inputValue],
      inputValue: ''
    }));
  }

  handleItemDelete (index) {
    // immutable
    // state 不允许我们做任何的改变
    this.setState((prevState) => {
      const list = [...prevState.list];
      list.splice(index, 1);
      return {
        list
      }
    });
  }

  getTodoItem () {
    return this.state.list.map((item, index) => {
      return (
        <div key={index}>
          {
            // this.handleItemDelete必须bind到父组件上
          }
          <TodoItem content={item} index={index}
            deleteItem={this.handleItemDelete} />
          {/*<li key={index} 
            dangerouslySetInnerHTML={{__html: item}}
            onClick={this.handleItemDelete.bind(this, index)}>
          </li>*/}
        </div>
      )
    })
  }
}

export default TodoList;
